package com.dly.hope.config;

import com.dly.hope.interceptor.JwtCheckInterceptor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * @author linyu.dai
 * @project myserve
 * @description 配置
 * @creat 2022/8/28 15:58:19
 */
@Configuration
public class Config implements WebMvcConfigurer {

    @Resource
    private JwtCheckInterceptor jwtCheckInterceptor;

    //添加拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtCheckInterceptor).addPathPatterns("/**");
    }

    @Bean(name = "domepool", destroyMethod = "shutdown")
    public ExecutorService makePool(){
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("guava-pool-%d").setDaemon(true).build();
        return new ThreadPoolExecutor(10,20,100L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(1024),threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 页面跨域访问Controller过滤
     *
     * @return
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许证书 不再默认开启
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("POST", "GET")
                // 跨域允许时间
                .maxAge(3600);
    }

    //配置自定义的json格式化器 解决枚举类型闯入为空的问题报错的问题
    @Bean
    public ObjectMapper getObjectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        return objectMapper;
    }

    //解决枚举类型闯入为空的问题
//    @Resource
//    private ObjectMapper objectMapper;
//
//    @PostConstruct //表示该类在注入之前调用
//    public void getObjectMapper(){
//        //配置格式化器枚举值可以为空
//        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
//    }
}
